import 'package:flutter/material.dart';
import 'package:flutterapp2/base/request/request.dart';
import 'package:flutterapp2/base/stickybar_delegate.dart';
import 'package:flutterapp2/building/buildinfo.dart';
import 'package:flutterapp2/base/request/base_request_page.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:flutterapp2/extension/extension.dart';

/// 吸顶+锚点联动
class TestStickyPage extends StatefulWidget {
  @override
  _TestStickyPageState createState() => _TestStickyPageState();
}

class _TestStickyPageState extends State<TestStickyPage> with SingleTickerProviderStateMixin {
  double tabBarHeight = 48;
  ScrollController _controller = new ScrollController();
  TabController _tabController;
  List<String> tabs = ["基本信息", "售卖资格", "服务信息"];
  var topY = 0.0; //测量column起始位置距离顶部的距离
  List<double> topOffsets; // // 测量锚点距离滑动区域顶部的距离
  var globalKeyTop = GlobalKey();
  List<GlobalKey> keys;

  @override
  void initState() {
    super.initState();
    keys = List.generate(tabs.length, (index) => GlobalKey());
    this._tabController = TabController(length: tabs.length, vsync: this);
    // 注册滑动监听
    _controller.addListener(() {
      var offset = _controller.offset;
      var find = false;
      for (int i = tabs.length - 1; i > 0; i--) {
        if (offset >= topOffsets[i]) {
          find = true;
          _tabController.animateTo(i);
          return;
        }
      }
      if (!find) _tabController.animateTo(0);
    });
  }

  _reMeasure() {
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      topY = getY(globalKeyTop.currentContext);
      topOffsets = List.generate(
          tabs.length,
          (index) => getY(keys[index].currentContext,
              dy: -topY - tabBarHeight + _controller.offset)); // 这里要加上偏移量
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("吸顶+锚点联动"),
      ),
      body: BaseRequestPage<BuildInfo>(
        request: _mockData,
        resultChecker: (data) => data != null,
        builder: _contentWidget,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          var sharedPreferences = await SharedPreferences.getInstance();
          sharedPreferences.setString("time", "2020-07-31");
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  Widget _contentWidget(BuildContext context, BuildInfo value, RetryFunction retryFunction) {
    _reMeasure();
    // 数据回来之后构建数据
    return CustomScrollView(
      key: globalKeyTop,
      controller: _controller,
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: Container(
            alignment: Alignment.center,
            color: Colors.deepOrangeAccent,
            height: 100,
            child: Text("top child"),
          ),
        ),
        // 吸顶
        SliverPersistentHeader(
          pinned: true,
          delegate: StickyBarDelegate(
            height: tabBarHeight,
            child: getTabBar(context),
          ),
        ),
        SliverToBoxAdapter(
          child: Column(
            children: <Widget>[
              Container(
                alignment: Alignment.center,
                width: double.infinity,
                height: 100,
                color: Colors.yellowAccent,
                child: Text("child2"),
              ),
              Container(
                key: keys[0],
                width: double.infinity,
                color: Colors.blue,
                child: Column(
                  children: <Widget>[
                    getTipsWidget(),
                    Container(
                      height: 200,
                      alignment: Alignment.center,
                      child: Text(tabs[0]),
                    )
                  ],
                ),
              ),
              Divider(
                height: 30,
                color: Colors.transparent,
              ),
              Container(
                key: keys[1],
                width: double.infinity,
                color: Colors.white,
//                height: 200,
                child: Column(
                  children: <Widget>[
                    Text(tabs[1]),
                    ListView.separated(
                      scrollDirection: Axis.horizontal,
                      separatorBuilder: (context, _index) => VerticalDivider(
                        width: 12,
                      ),
                      itemBuilder: (context, index) {
                        return Container(
                          width: 100,
                          height: 100,
                          color: Colors.blueAccent,
                          child: Text("$index").center(),
                        );
                      },
                      itemCount: 10,
                    ).size(height: 100), // CustomScrollView中嵌套横向ListView，ListView必须显示指明高度
                  ],
                ),
              ),
              Divider(
                height: 30,
                color: Colors.transparent,
              ),
              Container(
                margin: EdgeInsets.only(bottom: 500),
                height: 200,
                key: keys[2],
                alignment: Alignment.center,
                width: double.infinity,
                color: Colors.orange,
                child: Text(tabs[2]),
              )
            ],
          ),
        )
      ],
    );
  }

  Widget getTipsWidget() {
    return FutureBuilder<SharedPreferences>(
      future: SharedPreferences.getInstance(),
      builder: (context, snapshot) {
        var visible = true;
        if (snapshot.hasData && !snapshot.data.getString("time").isNullOrEmpty) {
          // fixme 重新计算高度
          visible = true;
          _reMeasure();
          return StatefulBuilder(
            builder: (_, stateSetter) => Container(
              height: 50,
              child: Card(
                child: Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Text(snapshot.data.getString("time") ?? ""),
                    Icon(Icons.clear)
                        .click(() {
                          stateSetter(() {
                            visible = false;
                          });
                          _reMeasure();
                          SharedPreferences.getInstance().then((sp) {
                            sp.clear();
                          });
                        })
                        .align(Alignment.centerRight)
                        .padding(EdgeInsets.only(right: 10)),
                  ],
                ),
              ),
            ).visible(visible),
          );
        }
        return const SizedBox.shrink();
      },
    );
  }

  Widget getTabBar(BuildContext context) {
    return TabBar(
      onTap: (index) {
        _controller.animateTo(topOffsets[index],
            duration: Duration(milliseconds: 200), curve: Curves.ease);
//        _controller.jumpTo()
      },
      controller: _tabController,
      labelColor: Colors.red,
      indicatorColor: Colors.red,
      indicatorSize: TabBarIndicatorSize.label,
      unselectedLabelColor: Colors.black,
      tabs: getTabs(),
    );
  }

  List<Widget> getTabs() {
    return tabs.map((f) {
      return Text(f);
    }).toList();
  }

  double getY(BuildContext buildContext, {double dy = 0.0}) {
    final RenderBox box = buildContext.findRenderObject();
    // 计算相对tabbar底部的距离
    final topLeftPosition = box.localToGlobal(Offset(0.0, dy));
    return topLeftPosition.dy;
  }

  Future<BuildInfo> _mockData() {
    return Future.delayed(Duration(seconds: 1), () {
      return BuildInfo(id: "1000", name: "张三");
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _tabController.dispose();
    super.dispose();
  }
}
